/*
 * Copyrignt (c) doubimeizhi.com. All Rights Reserved.
 * Author: mr.gao<fbg@live.com>
 * Created Time: 2016-12-05 09:48
 * Last Modified: 2017-08-07 10:50:35
 * File Name: qkcoupon/controllers/create_coupon.go
 * Description:
 */

package controllers

import (
	"encoding/json"
	"strings"

	"qkcoupon/db"
	"qkcoupon/errorcode"
	"qkcoupon/models"
	"qkcoupon/rpc/client/passport"
	"qkcoupon/utils"

	log "github.com/cihub/seelog"
)

type CreateCouponController struct {
	SCLoginedController
}

/*
 *@note  验证请求参数
 *param ccp: *TCreateCouponParam结构
 *@return (int64, int64, uint): (开始时间, 结束时间, 错误码)
 */
func (p *CreateCouponController) verification(req *models.PSQkCouponCreateCouponReq) (int64, int64, uint) {
	var errCode uint = errorcode.EC_GL_SUCCESS
	var startTick int64
	var endTick int64

	for {
		if !utils.CheckCType(req.Ctype) {
			log.Warnf("ctype:%d", req.Ctype)
			errCode = errorcode.EC_GL_INVALID_URL_PARAMS
			break
		}

		if !utils.CheckUType(req.Utype) {
			log.Warnf("utype:%d", req.Utype)
			errCode = errorcode.EC_GL_INVALID_URL_PARAMS
			break
		}

		if req.Ctype == int32(models.EQKCOUPON_CTYPE_RECHARGE_GIVE) {
			if req.Sum <= 0 || req.Discount <= 0 {
				log.Warn("sum <= 0 || discount <= 0")
				errCode = errorcode.EC_GL_INVALID_URL_PARAMS
				break
			}

			if req.Discount > req.Sum {
				log.Warnf("discount:%d > sum:%d", req.Discount, req.Sum)
				errCode = errorcode.EC_GL_INVALID_URL_PARAMS
				break
			}

			//清空数据
			if req.Rwids != nil {
				req.Rwids = nil
			}
		} else if req.Ctype == int32(models.EQKCOUPON_CTYPE_WASH_DISCOUNT) {
			if req.Discount <= 0 || req.Discount >= 1000 {
				log.Warn("discount <= 0 || discount >= 1000")
				errCode = errorcode.EC_GL_INVALID_URL_PARAMS
				break
			}

			//清空数据
			req.Sum = 0
			req.MaxDiscount = 0
		} else if req.Ctype == int32(models.EQKCOUPON_CTYPE_RECHARGE_CASHCOUPON) {
			if req.Sum <= 0 || req.Discount <= 0 {
				log.Warn("sum <= 0 || discount <= 0")
				errCode = errorcode.EC_GL_INVALID_URL_PARAMS
				break
			}

			if req.Discount > req.Sum {
				log.Warnf("discount:%d > sum:%d", req.Discount, req.Sum)
				errCode = errorcode.EC_GL_INVALID_URL_PARAMS
				break
			}

			//清空数据
			if req.Rwids != nil {
				req.Rwids = nil
			}

			//不限时段
			if req.TimeRanges != nil {
				for i := 0; i < len(req.TimeRanges.Time); i++ {
					req.TimeRanges.Time[i].Start = "00:00"
					req.TimeRanges.Time[i].End = "23:59"
				}
			}
		} else if req.Ctype == int32(models.EQKCOUPON_CTYPE_WASH_CASHCOUPON) {
			if req.Discount <= 0 {
				log.Warn("discount <= 0")
				errCode = errorcode.EC_GL_INVALID_URL_PARAMS
				break
			}

			//清空数据
			req.Sum = 0
			req.MaxDiscount = 0
		} else {
			//红包类型，清空数据
			req.Sum = 0
			req.Discount = 0
			req.MaxDiscount = 0
		}

		var ok bool

		ok = utils.CheckCreateTimeRange(req.TimeRanges)
		if !ok {
			log.Warnf("timeRange:%v", req.TimeRanges)
			errCode = errorcode.EC_GL_INVALID_URL_PARAMS
			break
		}

		startTick, endTick, ok = utils.GetStartAndEndTick(req.TimeRanges)
		if !ok {
			log.Warnf("timeRange:%v", req.TimeRanges)
			errCode = errorcode.EC_GL_INVALID_URL_PARAMS
			break
		}

		if req.Utype == int32(models.EQKCOUPON_UTYPE_APPOINT_MOBILE_USER) {
			//当为指定手机输入发优惠劵时，才判断手机列表
			if req.Mobiles == "" {
				log.Warn("mobiles==''")
				errCode = errorcode.EC_GL_INVALID_URL_PARAMS
				break
			}
		}

		break
	}

	return startTick, endTick, errCode
}

// @router /create [post]
func (p *CreateCouponController) CreateCoupon() {
	defer p.Output("CreateCoupon")

	data := p.Ctx.Input.RequestBody
	if len(data) == 0 {
		log.Warn("len(data)==0")
		p.Resp["code"] = errorcode.EC_GL_INVALID_URL_PARAMS
		return
	}

	log.Debug(string(data))

	req := &models.PSQkCouponCreateCouponReq{}
	err := json.Unmarshal(data, req)
	if err != nil {
		log.Warnf("%s", err.Error())
		p.Resp["code"] = errorcode.EC_GL_INVALID_URL_PARAMS
		return
	}

	//log.Debug(ccp)

	startTick, endTick, errCode := p.verification(req)
	if errCode != errorcode.EC_GL_SUCCESS {
		p.Resp["code"] = errCode
		return
	}

	cid, errCode := db.CreateCoupon(req, startTick, endTick, 0)
	if errCode != errorcode.EC_GL_SUCCESS {
		p.Resp["code"] = errCode
		return
	}

	if req.Utype == int32(models.EQKCOUPON_UTYPE_APPOINT_MOBILE_USER) {
		go p.dispatchCouponFromMobile(cid, strings.Split(req.Mobiles, ","))
	} else {
		go p.dispatchCoupon(cid)
	}

	p.Resp["code"] = errorcode.EC_GL_SUCCESS
}

/*
 *@note 分发优惠劵
 *param cid: 优惠劵流水编号
 *param token: Token
 */
func (p *CreateCouponController) dispatchCoupon(cid int64) {
	uids := []string{"2c82f921d67e439c8f5b04651d14bdb6", "50dcf070823a40af935ebca1598a62d1", "acf095a5a49f437ab152d7a105bec41b"}
	db.DispatchCoupon(cid, uids)
}

/*
 *@note 通过手机分发优惠劵
 *param cid: 优惠劵流水编号
 *param token: Token
 *param mobileList: 手机列表
 */
func (p *CreateCouponController) dispatchCouponFromMobile(cid int64, mobileList []string) {
	uids := p.getUids(mobileList)
	if len(uids) == 0 {
		return
	}

	db.DispatchCoupon(cid, uids)
}

/*
 *@note 通过手机获取用户ID列表
 *param token: Token
 *param mobileList: 手机列表
 *@return []string: 用户ID列表
 */
func (p *CreateCouponController) getUids(mobileList []string) []string {
	var uids = []string{}

	for _, mobile := range mobileList {
		if mobile == "" {
			continue
		}

		up, errCode := passport.GetUserProfileByAccount(mobile)
		if errCode != errorcode.EC_GL_SUCCESS {
			continue
		}

		if up.UserId == "" {
			continue
		}

		uids = append(uids, up.UserId)
	}

	log.Debugf("uids:%v", uids)

	return uids
}
